﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;


namespace Geek7Utils
{
    class Base64Helper
    {
        public static string Img2base64(string img_path)
        {

            if (string.IsNullOrEmpty(img_path))
                return "";

            //图片后缀格式
            int index = img_path.LastIndexOf('.');
            Image img = Image.FromFile(img_path);

            if (img != null && index != -1)
            {
                var suffix = img_path.Substring(index + 1, img_path.Length - 1 - index).ToLower();
                var format = ImageFormat.Png;
                switch (suffix) 
                {
                    case "jpg":
                    case "jpeg":
                        format = ImageFormat.Jpeg;
                        break;
                    case "bmp":
                        format = ImageFormat.Bmp;
                        break;
                    case "gif":
                        format = ImageFormat.Gif;
                        break;
                }

                using (MemoryStream ms = new MemoryStream())
                {
                    img.Save(ms, format);
                    byte[] data = ms.ToArray();
                    return $"data:image/{suffix};base64," + Convert.ToBase64String(data);
                }
            }


            return "";
        }

        public static Image Base642Image(string base64)
        {
            if (string.IsNullOrEmpty(base64))
            {
                throw new ArgumentNullException("base64参数不能为空");
            }
            byte[] bytes = Convert.FromBase64String(base64);
            Image img = null;
            using (MemoryStream memStream = new MemoryStream(bytes))
            {
                img = Image.FromStream(memStream);
            }
            return img;
        }
    
        public static string File2base64(string file)
        {
            return Convert.ToBase64String(File.ReadAllBytes(file));
        }
    }
}
